var responseText="";
var indexFileLocation;
var w3debug=false;
 
var domain="";
 
 function saveall(){ 
	//get the current page's url and save the page
	var pageurl = window.top.getBrowser().selectedBrowser.contentWindow.location.href; 
	//Use a filepicker to choose the folder where all the downloaded files are saved.
	var nsIFilePicker = Components.interfaces.nsIFilePicker;
	var fp = Components.classes["@mozilla.org/filepicker;1"]
			.createInstance(nsIFilePicker);
	fp.init(window, "Select a Folder to save the web pages", nsIFilePicker.modeGetFolder);
	var res = fp.show();
	var location="c:\\w3g_downloaded_sites\\";
	if (res == nsIFilePicker.returnOK) {
		  var file = fp.file; 
		  location = fp.file.path+"\\W3G_Downloaded_Sites\\"; 
	}else{ alert("pressed cancel"); return;} 
	//create a directory if not exists
	var dir = DirIO.open(location);
	if (!dir.exists()) { 
		var rv = DirIO.create(dir);
	} 	 
	
	indexFileLocation = location+"index.html";
	var filePath = createFolderStruct(location, pageurl);//indexFileLocation will changed to the correct location in here
	savePage(pageurl, filePath);			//Save the current (main) page.
	 indexFileLocation = indexFileLocation.replace(/\\/g,"/");	 
	var indexFileContent = "<html><head></head><body>If not automatically redirects, click <a href=\"file:///"+indexFileLocation+"\">here</a><script type=\"text/javascript\">window.location = 'file:///"+indexFileLocation+"';</script></body>";  
	var saveIndexPage = FileIO.open(location+"index.html");
	var writeStatus = FileIO.write(saveIndexPage, indexFileContent);
	if(!writeStatus) {
			alert("Error in writing the index file. Do you have enough permissions? ");
	}
	
	// Get all links in the current page and save them.
	var dom = gBrowser.contentDocument; 
	domain = dom.domain;
	var links = dom.getElementsByTagName("a");
	saveAllLinks(location,links);
	getCssFiles(location,dom);
	getImageFiles(location,dom); 
} 
function saveImages(dom,location){
	getImageFiles(location,dom); 
}
 
function getImageFiles(location,dom){
	
	var imageLinks = dom.getElementsByTagName("img");	//Get all the links  from the dom which are in <img> tag
	var imgs="";
	for (i=0;i<imageLinks.length;i++){  		//for every tag found, take the image source(src attribute) and save it to a file
		var imgsrc = imageLinks[i].src;
		imgs +=imgsrc+"\n";
		var imageFile = GetImageFromURL(imgsrc);
		
		var filePath = createFolderStruct(location,imgsrc); 
		var saveImage = FileIO.open(filePath);  
		var writeStatus = FileIO.write(saveImage, imageFile);
		if(!writeStatus && w3debug ) {
			alert("Error in writing the image file. Do you have enough permissions? ");
		} 
		imageLinks[i].src = imageLinks[i].src.replace(/ /g,"%20");
	} 
}

//extracts the image name from the image url and returns it as a string
function getImageName(imgsrc){			//ex: imgsrc = http://www.w3schools.com/images/h_logo.gif
	var startIndex = imgsrc.lastIndexOf("/"); 
	return imgsrc.substring(startIndex+1);	//returns "h_logo.gif"
}

//Retrieves the image from web and returns it as a file
function GetImageFromURL(url) { 
  var ioserv = Components.classes["@mozilla.org/network/io-service;1"] 
    .getService(Components.interfaces.nsIIOService); 
  var channel = ioserv.newChannel(url, 0, null); 
  var stream = channel.open(); 

  if (channel instanceof Components.interfaces.nsIHttpChannel && channel.responseStatus != 200) { 
    return "";
  }
  
  var bstream = Components.classes["@mozilla.org/binaryinputstream;1"] 
    .createInstance(Components.interfaces.nsIBinaryInputStream); 
  bstream.setInputStream(stream); 

  var size = 0; 
  var file_data = ""; 
  while(size = bstream.available()) { 
    file_data += bstream.readBytes(size);
  } 

  return file_data; 
} 

var writeErrorCount=0;
var alertCount=0;

//Downloads and saves a given pageurl at a given fileLocation with a given fileName 
function savePage(pageurl, filePath){ 
	if(filePath.indexOf(".asp") == filePath.length-4) {filePath = filePath+".html";}
	else if(filePath.indexOf(".php") == filePath.length-4) {filePath = filePath+".html"; }
	else if(filePath.indexOf(".jsp") == filePath.length-4) {filePath = filePath+".html"; }
	else if(filePath.indexOf(".aspx") == filePath.length-5) {filePath = filePath+".html"; }
	else if(filePath.indexOf(".cfm") == filePath.length-4) {filePath = filePath+".html"; }
	else if(!filePath.indexOf(".htm") == filePath.length-4 && !filePath.indexOf(".html") == filePath.length-5) {filePath = filePath+".html"; }	
 
	if(w3debug) alert("savePage.filePath=  "+filePath+", pageurl= "+pageurl);
	
	var req = new XMLHttpRequest();
	try{
		req.open("GET", pageurl, true);			//CHECK WHAT's Appropritate for async downloading(true/false)
		
		req.onreadystatechange = function(){
			if(req.readyState==4){
				var pageContent = req.responseText;
 
				alertCount++;
				var domainWithFolder = pageurl.substring(0,pageurl.lastIndexOf("/")+1);	//get the domain with the folder part from the url				
				var re = new RegExp(domainWithFolder, 'g');
				pageContent = pageContent.replace(re, ""); 
				var quoteSInd=0;
				var quoteEInd=5;  
				
				if(w3debug) alert("quoteE"+pageurl+quoteEInd);
				var changeCounter=0;
				while(pageContent.indexOf("href",quoteEInd) != -1){ 
					//get the link addresses from the page and rename them.
					var sInd = pageContent.indexOf(" href",quoteSInd); 
					quoteSInd =pageContent.indexOf("\"",sInd);
					quoteEInd =pageContent.indexOf("\"",quoteSInd+1);
					
					var ahrefOri =pageContent.substring(quoteSInd+1,quoteEInd);
					var ahref = ahrefOri.replace(/\s+/g,"");	//space removal
					 
					if(ahref.charAt(0) == "/"){
						ahref = "http://"+domain+ahref;
						if(w3debug) alert("starts with /: "+ahref);
					}
					
					//edit the pagecontents such that the asp/php/aspx are added the .html extension
					if(ahref.indexOf(".asp") == ahref.length-4){ ahref = ahref+".html";}
					else if(ahref.indexOf(".php") == ahref.length-4){ ahref = ahref+".html";}
					else if(ahref.indexOf(".jsp") == ahref.length-4){ ahref = ahref+".html";}
					else if(ahref.indexOf(".aspx") == ahref.length-5){ ahref = ahref+".html";}
					else if(ahref.indexOf(".cfm") == ahref.length-4){ ahref = ahref+".html";}
					else if(!ahref.indexOf(".htm") == ahref.length-4 && !ahref.indexOf(".html") == ahref.length-5) {ahref = ahref+".html"; }	
					
					if(w3debug) alert(ahref);
					var regx = new RegExp(ahrefOri, 'g');
					pageContent = pageContent.replace(regx,ahref);
					//pageContent = pageContent.replace(ahrefOri,ahref);
 
					ahref="";
					ahrefOri="";
					quoteEInd = quoteEInd+ domain.length;
					
					changeCounter++;
					if(changeCounter >50) break;
				} 
				changeCounter=0; 
				var saveLinkedPage = FileIO.open(filePath);
				
				var writeStatus = FileIO.write(saveLinkedPage,pageContent); 
				if(writeStatus) {}
				else {
					writeErrorCount++;
					if(writeErrorCount<3)
						alert("file write error. Do you have enough permissions? ");
				}

			}
		}
		req.send(null);
	}catch(err){
		alertCount++;
		if(alertCount<5) alert("Error in"+pageurl+": "+err); 
	}

}
